import json
import requests
import os
import base64

test_root = "xun_ji_test/data/image/recognition/test_1"

def download_and_save_image(image_url, root_dir, subfolder_name, filename):
    """
    下载图片并将其保存到指定的目录和文件名中。

    :param image_url: 图片的URL
    :param root_dir: 图片要保存到的根目录
    :param subfolder_name: 子文件夹名称
    :param filename: 保存的文件名
    """
    # 创建完整的文件路径
    folder_path = os.path.join(root_dir, subfolder_name)
    file_path = os.path.join(folder_path, filename)
    
    # 如果目标文件夹不存在，则创建它
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    
    # 发送HTTP GET请求下载图片
    response = requests.get(image_url)
    
    # 检查请求是否成功
    if response.status_code == 200:
        # 打开一个文件用于写入二进制模式，并保存图片内容
        with open(file_path, 'wb') as file:
            file.write(response.content)
        print(f"图片已保存到：{file_path}")
    else:
        print("图片下载失败。")

def extract_image_extension(image_url):
    # 找到链接中最后一个点的索引
    last_dot_index = image_url.rfind('.')
    
    # 通过索引获取后缀名
    if last_dot_index != -1:
        extension = image_url[last_dot_index:]
        return extension
    else:
        return "No extension found"

def read_dicts_from_file(filename):
    """
    读取测试集文本文件，每行都是一个JSON格式的字典，
    并将这些字典作为列表返回。

    :param filename: 文本文件的路径
    :return: 包含所有字典的列表
    """
    result = []
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            # 将每行文本转换成字典
            data_dict = json.loads(line)
            result.append(data_dict)
    return result


dicts_list = read_dicts_from_file("xun_ji_test/data/label/recognition/test_1.txt")

def Download_imgs():
    for img in dicts_list:
        image_url = img["LINK"]
        subfolder_name  = img["ZI"]
        font = img["Font"].lower()
        id = img["ID"]
        extension = extract_image_extension(image_url)
        if extension != ".gif":
            filename = font + "-" + str(id) + extension
            download_and_save_image(image_url, test_root, subfolder_name, filename)
            print(image_url)


if __name__ == '__main__':
    Download_imgs()